package controller;

import java.util.Locale;
import java.util.ResourceBundle;
import gameapi.Player;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import db.RegisteredUserDb;

@ManagedBean
@SessionScoped
public class RegisterController {

	private static final String LOGIN_VIEW = "/login.xhtml";
	@ManagedProperty(value = "#{player}")
	private Player player;
	private RegisteredUserDb userDatabase = RegisteredUserDb.getInstance();
	private boolean showpersonaldata = false;
	private UIComponent submitButton;

	public RegisterController() {
	}

	public String register() {

		String goToView = "";
		if (player != null) {
			try {
				userDatabase.addPlayer(player);
				goToView = LOGIN_VIEW;
			} catch (Exception e) {

				FacesContext context = FacesContext.getCurrentInstance();
				Locale language = context.getViewRoot().getLocale();
				ResourceBundle res = ResourceBundle.getBundle("i18n", language);
				String message = (String) res.getObject("playeralreadyexists");
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
						message, null);
				context.addMessage(submitButton.getClientId(context), msg);
			}
		}
		return goToView;
	}

	public void setPlayer(Player player) {
		System.out.println("SetPlayer");
		this.player = player;
	}

	public Player getPlayer() {
		return this.player;
	}

	public boolean isPersonalData() {
		return showpersonaldata;
	}

	public void setPersonalData(boolean showpersonaldata) {
		this.showpersonaldata = showpersonaldata;
	}

	public void togglePersonalData(ValueChangeEvent event) {
		showpersonaldata = !showpersonaldata;
	}

	public void setSubmitButton(UIComponent component) {
		this.submitButton = component;
	}

	public UIComponent getSubmitButton() {
		return submitButton;
	}
}
